package com.guagua.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guagua.blog.dto.CommentDTO;
import com.guagua.blog.entity.Article;
import com.guagua.blog.entity.Comment;
import com.guagua.blog.mapper.CommentMapper;
import com.guagua.blog.service.ArticleService;
import com.guagua.blog.service.CommentService;
import com.guagua.blog.vo.CommentVO;
import com.guagua.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final ArticleService articleService;

    @Override
    @Transactional
    public Comment addComment(CommentDTO commentDTO, Long userId) {
        // 创建评论
        Comment comment = new Comment();
        comment.setContent(commentDTO.getContent());
        comment.setArticleId(commentDTO.getArticleId());
        comment.setUserId(userId);
        comment.setParentId(commentDTO.getParentId());
        comment.setReplyUserId(commentDTO.getReplyUserId());
        comment.setCreateTime(LocalDateTime.now());
        
        // 保存评论
        boolean saved = save(comment);
        if (!saved) {
            throw new BusinessException("评论保存失败");
        }
        
        // 更新文章评论数
        boolean updated = articleService.lambdaUpdate()
            .eq(Article::getId, comment.getArticleId())
            .setSql("comment_count = comment_count + 1")
            .update();
            
        if (!updated) {
            throw new BusinessException("更新评论数失败");
        }
        
        return comment;
    }

    @Override
    public List<CommentVO> getCommentsByArticleId(Long articleId) {
        return baseMapper.selectCommentsByArticleId(articleId);
    }

    @Override
    @Transactional
    public boolean deleteComment(Long commentId, Long userId) {
        // 获取评论信息
        Comment comment = getById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }
        
        // 检查权限
        if (!comment.getUserId().equals(userId)) {
            throw new BusinessException("无权删除他人评论");
        }
        
        // 删除评论
        boolean removed = removeById(commentId);
        if (!removed) {
            throw new BusinessException("删除评论失败");
        }
        
        // 更新文章评论数
        boolean updated = articleService.lambdaUpdate()
            .eq(Article::getId, comment.getArticleId())
            .setSql("comment_count = comment_count - 1")
            .update();
            
        if (!updated) {
            throw new BusinessException("更新评论数失败");
        }
        
        return true;
    }
} 